﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NaviCar.DB.Auxiliar;
using NMEAParser.NMEA0183;
using NaviCar.DB;
using System.IO;
using System.Xml;
using NaviCar.Servico.Query;

namespace NaviCar.Servico.Entidades
{
    public class ServicoNavegacao : ServicoBase<NaviCar.DB.Veiculo>
    {
        public Rastreamento RecuperarUltimoRegistro(int codigo)
        {
            Rastreamento retorno = (from t in this.repositorio.RecuperarTodos()
                                    let pos = (from s in t.Posicao orderby s.Data descending select s).FirstOrDefault()
                                    select new Rastreamento { Placa = t.Placa, CodigoVeiculo = codigo, Latitude = pos.Latitute, Longitude = pos.Longitude, Data = pos.Data, Intervalo = t.Intervalo * 1000 }).FirstOrDefault();

            return retorno;
        }

        public void ArmazenarDadosGPS(string dados, int sistema)
        {
            string[] dadosVeiculo = dados.Substring(0,dados.IndexOf("GPRMC")-1).Split(',');
            string strGPRMC = dados.Substring(dados.IndexOf("GPRMC"));
            GPRMCParser parser = new GPRMCParser();
            GPRMC sentence = null;

            if (parser.IsSentence(strGPRMC))
            {
                sentence = (GPRMC)parser.ParseSentence(strGPRMC);
            }


            Veiculo veiculo  = this.repositorio.RecuperarTodos().Where(f=>f.ChaveRastreador == dadosVeiculo[0]).SingleOrDefault();

            if(veiculo != null)
            {
                Posicao posicao = new Posicao();

                posicao.Data = sentence.TimeStamp;
                posicao.Latitute = sentence.LatLon.Latitude.ToString();
                posicao.Longitude = sentence.LatLon.Longtitude.ToString();


                veiculo.Posicao.Add(posicao);
            }

            this.repositorio.Salvar();
        }


        public string RecuperarArquivoKM(DateTime inicio, DateTime fim,int codigoVeiculo)
        {
            ServicoBase<Veiculo> srvVeiculo = new ServicoBase<Veiculo>();
            Veiculo veiculo = srvVeiculo.RecuperarPorID(codigoVeiculo);

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            XmlTextWriter writer = new XmlTextWriter(sw);
            writer.Indentation = 2;
            XmlDocument doc = new XmlDocument();// Create the XML Declaration, and append it to XML document
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0","UTF-8", null);
            doc.AppendChild(dec);// Create the root element
            XmlElement root = doc.CreateElement("kml");
            root.SetAttribute("xmlns", "http://earth.google.com/kml/2.1");
            doc.AppendChild(root);

            XmlElement documento = doc.CreateElement("Document");
            root.AppendChild(documento);
            XmlElement name = doc.CreateElement("name");
            documento.AppendChild(name);
            name.InnerText = string.Format("Placa: {0}   Incio: {1}   Fim: {2}", veiculo.Placa, inicio.ToShortDateString(), fim.ToShortDateString());
            XmlElement description = doc.CreateElement("description");
            documento.AppendChild(description);
            description.InnerText = string.Format("Placa: {0}   Incio: {1}   Fim: {2}", veiculo.Placa, inicio.ToShortDateString(), fim.ToShortDateString());
            XmlElement Style = doc.CreateElement("Style");
            documento.AppendChild(Style);
            
            XmlElement LineStyle = doc.CreateElement("LineStyle");
            LineStyle.SetAttribute("id","blue");
            Style.AppendChild(LineStyle);
            XmlElement color = doc.CreateElement("color");
            color.InnerText = "ffff0000";
            LineStyle.AppendChild(color);
            XmlElement width = doc.CreateElement("width");
            width.InnerText = "4";
            LineStyle.AppendChild(width);

            XmlElement Placemark = doc.CreateElement("Placemark");
            documento.AppendChild(Placemark);

            XmlElement nameP = doc.CreateElement("name");
            nameP.InnerText = "Blue Line";
            Placemark.AppendChild(nameP);
            XmlElement styleUrl = doc.CreateElement("styleUrl");
            styleUrl.InnerText = "#blue";
            Placemark.AppendChild(styleUrl);
            XmlElement LineString = doc.CreateElement("LineString");
            Placemark.AppendChild(LineString);

            XmlElement altitudeMode = doc.CreateElement("altitudeMode");
            altitudeMode.InnerText = "relative";
            LineString.AppendChild(altitudeMode);
            XmlElement coordinates = doc.CreateElement("coordinates");
            LineString.AppendChild(coordinates);
            
            ServicoBase<Posicao> servico = new ServicoBase<Posicao>();

            fim = fim.AddHours(23).AddMinutes(59);
            var lista = servico.RecuperarTodos().Where(f => (f.CodigoVeiculo == codigoVeiculo) && (f.Data > inicio && f.Data <= fim)).Select(f => string.Format("{0},{1},{2}", f.Longitude, f.Latitute, f.Velocidade.ToString().Replace(",","."))).ToList();

            StringBuilder coordenadas = new StringBuilder();
            foreach (string item in lista)
	        {
		        coordenadas.AppendLine(item);
	        }

            coordinates.InnerText = coordenadas.ToString();


            doc.WriteContentTo(writer);

            return sb.ToString();
            //<?xml version="1.0" encoding="UTF-8"?>
            //<kml xmlns="http://earth.google.com/kml/2.1">
            //    <Document>
            //        <name>Chicago Transit Map</name>
            //        <description>Chicago Transit Authority train lines</description>

            //        <Style id="blueLine">
            //            <LineStyle>
            //                <color>ffff0000</color>
            //                <width>4</width>
            //            </LineStyle>
            //        </Style>
            //       <Placemark>
            //          <name>Blue Line</name>
            //          <styleUrl>#blueLine</styleUrl>
            //          <LineString>
                            //<altitudeMode>relative</altitudeMode>
                            //<coordinates>
        }

    }
}
